package com.salon.client.tabItems;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.IconAlign;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.Style.VerticalAlignment;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Html;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.HTMLTable.Cell;
import com.salon.client.GreetingServiceAsync;
import com.salon.client.Salon;
import com.salon.client.beans.WorkDayBean;

public class WorkDateTabItemPanel extends ContentPanel {
	private final String styleCell = "salon-SelectedCell";
	private ToolBar toolbar = new ToolBar();
	private FlexTable table = null;
	private int month;
	private int year;
	private List<WorkDayBean> workDays = null;
	private String[] months = new String[]{
			"Январь",
			"Февраль",
			"Март",
			"Апрель",
			"Май",
			"Июнь",
			"Июль",
			"Август",
			"Сентябрь",
			"Октябрь",
			"Ноябрь",
			"Декабрь",
			};
	
	public WorkDateTabItemPanel() {
		setScrollMode(Scroll.AUTO);
		setBodyBorder(false);
		setHeading("Рабочие дни");
		setButtonAlign(HorizontalAlignment.CENTER);
		//setLayout(new FitLayout());
		toolbar.setBorders(true);
		toolbar.setAlignment(HorizontalAlignment.CENTER);
		setBottomComponent(toolbar);
		
		Date now = new Date();
		month = now.getMonth();
		year = now.getYear() + 1900;
		
		initComponents();
	}
	
	protected void initComponents() {
		Button refresh = new Button("Обновить");
		refresh.setIcon(IconHelper.createStyle("brit-refresh-button"));
		refresh.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				reInitWorkDayTable();
				
			}
			
		});
		
		toolbar.add(refresh);
		Button prev = new Button("Предыдущий месяц");
		prev.setIcon(IconHelper.createStyle("salon-prev"));
		prev.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				prevMonth();
				reInitWorkDayTable();
			}
			
		});
		
		toolbar.add(prev);
		Button next = new Button("Следующий месяц");
		next.setIconAlign(IconAlign.RIGHT);
		next.setIcon(IconHelper.createStyle("salon-next"));
		next.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				nextMonth();
				reInitWorkDayTable();
			}
			
		});
		
		toolbar.add(next);
		
		table = new FlexTable();
		table.setWidth("100%");
		//table.setHeight("500px");
		table.setStyleName("salon-Cell");
		table.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				Cell cell = table.getCellForEvent(event);
				selectCell(cell.getCellIndex(), cell.getRowIndex());
			}
			
		});
		reInitWorkDayTable();
		add(table);
		
	}
	
	protected void reInitWorkDayTable() {
		((GreetingServiceAsync) Registry.get(Salon.SERVICE)).
		getWorkDays(year, month, new AsyncCallback<List<WorkDayBean>>() {

			@Override
			public void onFailure(Throwable caught) {
				Info.display("Не удалось получить", "рабочие часы");
				
			}

			@Override
			public void onSuccess(List<WorkDayBean> result) {
				workDays = result;
				setHeading(months[month] + " " + year + " года");
				//Info.display("!!!!", "рабочие часы");
				clearTable();
				List<Integer> sumCost = new ArrayList<Integer>();
				for (int i = 0; i < workDays.size(); i++) {
					if (i == 0) {
						table.setWidget(0, 0, new Html(""));
						for (int j = 0; j < workDays.get(0).getList().size(); j++) {
							table.setHTML(i, j + 1, new Integer(j + 1).toString());
							table.getCellFormatter().setHorizontalAlignment(i, j + 1, HasHorizontalAlignment.ALIGN_CENTER);
							table.getCellFormatter().setWidth(i, j + 1, "50px");
							table.getCellFormatter().setHeight(i, j + 1, "30px");
							sumCost.add(0);
						}
					}
					table.setWidget(i + 1, 0, new Html(result.get(i).getMasterName()));
					table.getCellFormatter().setWidth(i + 1, 0, "80px");
					table.getCellFormatter().setHeight(i + 1, 0, "40px");
					for (int j = 0; j < workDays.get(i).getList().size(); j++) {
						if (workDays.get(i).getCosts().get(j) != 0) {
							sumCost.set(j, sumCost.get(j) + workDays.get(i).getCosts().get(j));
							table.getCellFormatter().setHorizontalAlignment(i + 1, j + 1, HasHorizontalAlignment.ALIGN_CENTER);
							table.setHTML(i + 1, j + 1, "" + workDays.get(i).getCosts().get(j));
						}
						else {
							table.setHTML(i + 1, j + 1, "&nbsp");
						}
						table.getCellFormatter().setWidth(i + 1, j + 1, "50px");
						table.getCellFormatter().setHeight(i + 1, j + 1, "40px");
						if (workDays.get(i).getList().get(j)) {
							table.getCellFormatter().addStyleName(i + 1, j + 1, styleCell);
						}
					}
					
					if (i == workDays.size() - 1) {
						table.setWidget(i + 2, 0, new Html("Итого:"));
						for (int j = 0; j < sumCost.size(); j++) {
							table.setHTML(i + 2, j + 1, "" + sumCost.get(j));
							table.getCellFormatter().setHorizontalAlignment(i + 2, j + 1, HasHorizontalAlignment.ALIGN_CENTER);
							table.getCellFormatter().setWidth(i + 2, j + 1, "50px");
							table.getCellFormatter().setHeight(i + 2, j + 1, "30px");
						}
					}
				}
				
			}
			
		});
	}
	
	private void clearTable() {
		/*for (int i = 0; i < table.getRowCount(); i ++) {
			for (int j = 0; j < table.getCellCount(i); j ++) {
				table.clearCell(i, j);
			}
			table.removeRow(table.getRowCount() - i - 1);
		}*/
		for (int i = table.getRowCount() - 1; i >= 0; i --) {
			table.removeRow(i);
		}
	}
	protected void selectCell(int col, int row) {
		if ((col == 0) || (row == 0)) {
			return;
		}
		if (table.getCellFormatter().getStyleName(row, col).equals(styleCell)) {
			deleteWorkDay(col, row);
		}
		else {
			addWorkDay(col, row);
		}
	}
	
	private void addWorkDay(final int col, final int row) {
		if (row - 1 >= workDays.size()) {
			return;
		}
		WorkDayBean bean = workDays.get(row - 1);
		int masterId = bean.getMasterId();
		int day = col;
		
		((GreetingServiceAsync) Registry.get(Salon.SERVICE)).
		addWorkDay(masterId, day, month, year, new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				Info.display("Не удалось добавить", " рабочий день");
			}

			@Override
			public void onSuccess(Void result) {
				table.getCellFormatter().addStyleName(row, col, "salon-SelectedCell");
				workDays.get(row - 1).getList().set(col - 1, true);
			}
			
		});
	}
	
	private void deleteWorkDay(final int col, final int row) {
		if (row - 1 >= workDays.size()) {
			return;
		}
		WorkDayBean bean = workDays.get(row - 1);
		int masterId = bean.getMasterId();
		int day = col;
		
		((GreetingServiceAsync) Registry.get(Salon.SERVICE)).
		deleteWorkDay(masterId, day, month, year, new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				Info.display("Не удалось удалить", " рабочий день");
			}

			@Override
			public void onSuccess(Void result) {
				table.getCellFormatter().removeStyleName(row, col, "salon-SelectedCell");
				workDays.get(row - 1).getList().set(col - 1, false);
			}
			
		});
	}
	
	private void nextMonth() {
		if (month == 11) {
			month = 0;
			++year;
		}
		else {
			++month;
		}
	}
	private void prevMonth() {
		if (month == 0) {
			month = 11;
			--year;
		}
		else {
			--month;
		}
	}
}
